package com.michael.leetcode;

import org.junit.Test;

public class DeleteDuplicates_82 {

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    /**
     * 82. 删除排序链表中的重复元素 II
     * 给定一个已排序的链表的头 head ， 删除原始链表中所有重复数字的节点，只留下不同的数字 。返回 已排序的链表 。
     *
    示例 1：
    输入：head = [1,2,3,3,4,4,5]
    输出：[1,2,5]

    示例 2：
    输入：head = [1,1,1,2,3]
    输出：[2,3]

    提示：
    链表中节点数目在范围 [0, 300] 内
    -100 <= Node.val <= 100
    题目数据保证链表已经按升序 排列
     */
    public ListNode deleteDuplicates(ListNode head) {
        if (head== null || head.next == null){
            return head;
        }

        ListNode o = head;
        ListNode t = head.next;
        boolean d = false;
        while ( t != null){
            if (o.val == t.val){
                t = t.next;
                d = true;
            }else {
                if (d){
                    o.val = t.val;
                    o.next = t.next;
                    d = false;
                } else {
                    o = o.next;
                }
                t = o.next != null? o.next: null;
            }
        }



        if (d && t== null){
           ListNode c = head;
           if (c.equals(o)){
               return null;
           }
            while (!c.next.equals(o)){
                c = c.next;
            }
            c.next = null;
        }
        return head;
    }

    @Test
    public void test(){
//        ListNode node5 = new ListNode(5);
//        ListNode node4 = new ListNode(4, node5);
        ListNode node41 = new ListNode(4 );
        ListNode node3 = new ListNode(4, node41);
        ListNode node31 = new ListNode(4, node3);
        ListNode node2 = new ListNode(4, node31);
        ListNode node1 = new ListNode(4, node2);

        deleteDuplicates(node1);
    }
}